import { Component, OnInit, Input } from '@angular/core';
import { StatisticService } from '../../services/statistic.service';
import { MySelection } from 'app/modules/base/selection';
import { Zone } from 'app/modules/zone/services/zone.service';
import { ReplaySubject } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { LoginService } from 'app/modules/login/services/login.service';

const StoreKey = 'system_upgrade_zones';

@Component({
  selector: 'm-system-upgrade',
  templateUrl: './system-upgrade.component.html',
  styleUrls: ['./system-upgrade.component.scss'],
})
export class SystemUpgradeComponent implements OnInit {
  constructor(private statisticService: StatisticService, private loginService: LoginService) {}
  @Input() zone: Zone;
  color = ['green', 'red', 'gray'];
  selection = new MySelection<Zone>('id');
  user = this.loginService.User$.toPromise();
  zoneIDs$ = new ReplaySubject<number[]>();
  upgrade$ = this.zoneIDs$.pipe(
    switchMap(zoneIDs => this.statisticService.systemUpgrade(...zoneIDs)),
  );

  ngOnInit() {
    this.init();
  }
  async storeKey() {
    const user = await this.user;
    const zid = this.zone ? this.zone.id : -1;
    return `${user.uid}_${StoreKey}_${zid}`;
  }
  async init() {
    if (this.zone) {
      this.zoneIDs$.next([this.zone.id]);
      return;
    }
    const key = await this.storeKey();
    const value = localStorage.getItem(key);
    if (value) {
      const ids = JSON.parse(value) as number[];
      this.zoneIDs$.next(ids);
    } else {
      this.zoneIDs$.next([]);
    }
  }
  async change() {
    const key = await this.storeKey();
    const ids = this.selection.keys<number>();
    if (!ids.length) {
      localStorage.removeItem(key);
      this.zoneIDs$.next([]);
      return;
    }
    localStorage.setItem(key, JSON.stringify(ids));
    this.zoneIDs$.next(ids);
  }
}
